<?php


namespace app\admin\controller;
use app\admin\model\Goods as GoodsModel;
use app\admin\model\GoodsAttr as GoodsAttrModel;
use app\admin\model\GoodsType as GoodsTypeModel;
use app\admin\model\GoodsBrand as GoodsBrandModel;

use app\admin\model\Receive;
use think\Request;
use think\Paginator;    //分页
use think\File;         //上传
use think\Image;        //图片

class Goods extends Base
{
    //后台首页页面
    public function index()
    {
        $webSite = WEB_SITE;
        $staticAdmin = STATIC_ADMIN;

        //传值,渲染页面
        $this->assign([
            'staticAdmin' => $staticAdmin,
            'webSite'    =>  $webSite
        ]);
        return $this->fetch();

    }

    //遍历商品信息,分页
    public function lists()
    {
        //常量
        $webSite = WEB_SITE;
        $staticAdmin = STATIC_ADMIN;

        //遍历商品表
        $goods = GoodsModel::where(['goods_del'=>0])->paginate(4);
        $goodsPage = $goods->render();

        $this->assign([
            'webSite' => $webSite,
            'staticAdmin' => $staticAdmin,
            'goods' => $goods,
            'goodsPage' => $goodsPage,

        ]);

        return $this->fetch();

    }

    //ajax修改标记位
    public function flag()
    {
        $gid = Request::instance()->param('gid');
        $data = [];

        //精品,注意:if判断时,0返回false
        if (Request::instance()->param('elite') > -1) {

            $data['is_elite'] = Request::instance()->param('elite');
        } else if (Request::instance()->param('new') > -1) {

            //新品
            $data['is_new'] = Request::instance()->param('new');
        } else if (Request::instance()->param('hot') > -1) {

            //热销
            $data['is_hot'] = Request::instance()->param('hot');
        } else if (Request::instance()->param('receive') > -1) {

            $sale = Request::instance()->param('receive');
            $msg =  $sale == 1 ? '上架成功' : '下架成功';
            $msg2 =  $sale == 1 ? '上架失败' : '下架失败';

            //修改上,下架状态
            $data['is_on_sale'] = $sale;
        } else if (Request::instance()->param('delete') > -1) {

            $data['goods_del'] = Request::instance()->param('delete');

        } else if (Request::instance()->param('disDel') > -1) {

            $data['goods_del'] = Request::instance()->param('disDel');
        }

        //当前时间datetime格式
        $currTime = date('Y-m-d H:i:s',time());
        $data['update_time'] = $currTime;

        //修改数据库
        $goods = GoodsModel::where(['goods_id'=>$gid])->update($data);
        //dump($goods);
        //dump($data);

        //是否修改成功
        if ($goods) {

            $tip = '修改成功';
            if (Request::instance()->param('receive') > -1) {

                $tip = $msg;
            } else if (Request::instance()->param('delete') > -1) {

                $tip = '删除成功';
            } else if (Request::instance()->param('disDel') > -1) {

                $tip = '恢复成功';
            }

            echo json_encode(['state'=>1,'tip'=>"$tip"]);

        } else {

            $tip = '修改失败';
            if (Request::instance()->param('receive') > -1) {

                $tip = $msg2;
            } else if (Request::instance()->param('delete') > -1) {

                $tip = '删除失败';
            } else if (Request::instance()->param('disDel') > -1) {

                $tip = '恢复失败';
            }
            echo json_encode(['state'=>2,'tip'=>"$tip"]);
        }
    }

    //查询分页
    public function sel()
    {
        $data1['goods_card'] = Request::instance()->param('where');
       // $data2['goods_name'] = Request::instance()->param('where');

        //--精品/新品/热销
        if (Request::instance()->param('where1')) {

            $where1 = Request::instance()->param('where1');
            $flag = 'is_' . $where1;
            $data1[$flag] = 1;
            //$data2[$flag] = 1;
        }
        //dump($data1);
        //dump($data2);

        //查询
        $goods1 = GoodsModel::where($data1)->select();    //商品编号
        //$goods2 = GoodsModel::where($data2)->select();  //商品名

        //是否存在
        //if ($goods1 || $goods2) {
        if ($goods1) {

            //$goods = is_null($goods1) ? $goods2 : $goods1;
            //dump($goods1);
            foreach ($goods1 as $g) {

                $res[]['small_logo'] = $g->small_logo;
                $res[]['goods_name'] = $g->goods_name;
                $res[]['goods_card'] = $g->goods_card;
                $res[]['market_price'] = $g->market_price;
                $res[]['shop_price'] = $g->shop_price;
                $res[]['stock_num'] = $g->stock_num;
                $res[]['is_elite'] = $g->is_elite;
                $res[]['is_new'] = $g->is_new;
                $res[]['is_hot'] = $g->is_hot;
                $res[]['is_on_sale'] = $g->is_on_sale;

                $res[]['goods_id'] = $g->goods_id;
            }
            //dump($res);
            echo json_encode(['state'=>1,'tip'=>'存在','res'=>$res]);
        } else {

            echo json_encode(['state'=>2,'tip'=>'你查询的商品名/商品编号不存在']);
        }
    }

    //添加商品的页面
    public function increase()
    {
        $webSite = WEB_SITE;
        $staticAdmin = STATIC_ADMIN;

        //遍历属性表
        $type = GoodsTypeModel::all();

        //遍历品牌表
        $brand = GoodsBrandModel::all();

        //遍历分类表
        $attr = GoodsAttrModel::all();

        //传值,渲染页面
        $this->assign([
            'webSite' => $webSite,
            'staticAdmin' => $staticAdmin,
             'type' => $type,
            'attr' => $attr,
            'brand' => $brand,
        ]);

        return $this->fetch();
    }

    //商品图片上传
    public function upload()
    {
        //同一个用户一次上传一张
       if (session('pic2')) {

            //修改页面
            if (Request::instance()->param('gid')) {

                $gid = Request::instance()->param('gid');
                $this->error('你已添加过头像', 'detail?gid=' . $gid);
               // dump($gid);
            } else {

                $this->error('你已添加过头像', 'increase');
            }
        }

        //获取图片信息
        $file = request()->file('img');
        //dump($file);

        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){

            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.'goods');

            if($info){

                //将路径保存到全局变量中
                $txPath = 'uploads'.DS.'goods'.DS.$info->getSaveName();
                //截取文件路径,使得同一商品的图片保存在当天的文件夹中
                $pos = strrpos($txPath , '.');
                $path = substr($txPath ,  0 ,$pos);
                //dump($txPath);
                //dump($pos);
                //dump($path);

                $image = Image::open($file);
               // dump($image);

                //拼接生成大,中,小图片文件名
                $big = $path .'_big.png';
                $mid = $path . '_mid.png';
                $small = $path .'_small.png';

                // 按照比例生成缩略图并保存
                $image->thumb(800, 800)->save($big);
                $image->thumb(350, 350)->save($mid);
                $image->thumb(60, 60)->save($small);

               //拼接图片路径,保存到session
                $picPath = $big . '+' . $mid . '+' . $small;
                session('pic2',$picPath);
                //dump(session('pic2'));

                //根据gid,判断是修改页面
                if (Request::instance()->param('gid')) {

                    $gid = Request::instance()->param('gid');
                    $this->success('上传成功','detail?gid=' . $gid);
                } else {

                    $this->success('上传成功','increase');
                }

            }else{
                // 上传失败获取错误信息
                $err = $file->getError();

                //根据gid,判断是修改页面
                if (Request::instance()->param('gid')) {

                    $gid = Request::instance()->param('gid');
                    $this->error("$err", 'detail?gid=' . $gid);
                } else {

                    $this->error("$err", 'increase');
                }
            }
        } else {

            //根据gid,判断是修改页面
            if (Request::instance()->param('gid')) {

                $gid = Request::instance()->param('gid');
                $this->error('上传失败,请重新上传','detail?gid=' . $gid);
            } else {

                $this->error('上传失败,请重新上传','increase');
            }
        }
    }

    //查询商品编号
    public function card()
    {
        $card = Request::instance()->param('card');

        //查询
        $goods = GoodsModel::where(['goods_card'=>"$card"])->select();

        //编号是否存在
        if ($goods) {

            echo json_encode(['state'=>1, 'tip'=>'该编号已存在,请重新输入']);
        } else {

            echo json_encode(['state'=>2, 'tip'=>'该编号合法']);
        }
    }

    //添加商品
    public function add()
    {
        //接收值
        $post = Request::instance()->param();

        //商家id
        //dump(session('shop_id'));
        $data['shop_id'] = session('shop_id');
        //商品图片处理
        //$image = session('pic2');
        if (session('pic2')) {

            $img = explode('+',session('pic2'));
            $data['big_logo'] = $img[0];
            $data['mid_logo'] = $img[1];
            $data['small_logo'] = $img[2];
        }

        //字段
        $data['goods_name'] = $post['name'];
        $data['goods_card'] = $post['card'];
        $data['brand_id'] = $post['brand'];
        $data['attr_id']  = $post['attr'];
        $data['type_id']  = $post['type'];
        $data['weight']   = $post['weight'];
        $data['weight_unit'] = $post['unit'] == 1 ? 'g' : 'kg';
        $data['shop_price']  = $post['price'];
        $data['market_price'] = $post['market'];
        $data['stock_num']  = $post['stock'];

        //是否上架
        $data['is_on_sale'] = $post['onSale'] == 'yes' ? 1 : 0 ;

        //若状态存在
        if ($post['state']) {

            //初值
            $data['is_new'] = 0;
            $data['is_elite'] = 0;
            $data['is_hot'] = 0;

            //切割字符串
            $state = explode('_',$post['state']);
            //dump($state);

            //若参数存在数组中
            if (in_array('new',$state)) {   //新品
                $data['is_new'] = 1;
            }
            if (in_array('elite',$state)) { //精品
                $data['is_elite'] = 1;
            }
            if (in_array('hot',$state)) {   //热销
                $data['is_hot'] = 1;
            }

        } else {
            $data['is_new'] = 0;
            $data['is_elite'] = 0;
            $data['is_hot'] = 0;
        }

        //若有描述
        if ($post['desc']) {
            $data['goods_desc'] = $post['desc'];
        }

        //当前时间datetime

        //防止编号重名
        $card = $post['card'];
        $data2['brand_id'] = $post['brand'];
        $data2['attr_id']  = $post['attr'];
        $data2['type_id']  = $post['type'];
        $data2['goods_name']  = $post['name'];

        //查询
        $res = GoodsModel::where(['goods_card'=>"$card"])->select();
        $res2 = GoodsModel::where($data2)->select();    //防止属性,品牌,分类同时相同
        //dump($data);
        //dump($res);
        //dump($res2);

        //编号是否存在
        if ($res) {

            echo json_encode(['state'=>1, 'tip'=>'该编号已存在,请重新输入']);
        } else {

            if ($res2) {

                echo json_encode(['state'=>5, 'tip'=>'已有相同商品存在,请更改商品名/品牌/属性/分类']);
            } else {

                //插入数据库
                $goods = GoodsModel::create($data);
                //dump($goods);

                //是否添加成功
                if ($goods) {

                    //清除上传session
                    if (session('pic2')) {
                        session('pic2',null);
                    }

                    echo json_encode(['state'=>3,'tip'=>'添加商品成功']);
                } else {

                    echo json_encode(['state'=>4,'tip'=>'添加商品失败']);
                }
            }

        }
    }


    //当前商品的详情
    public function detail()
    {
        $gid = Request::instance()->param('gid');
       // dump($gid);

        //遍历商品表
        $goods = GoodsModel::where(['goods_del'=>0,'goods_id'=>$gid])->paginate(4);
        $goodsPage = $goods->render();

        //遍历属性表
        $type = GoodsTypeModel::all();

        //遍历品牌表
        $brand = GoodsBrandModel::all();

        //遍历分类表
        $attr = GoodsAttrModel::all();

        //传值,渲染页面
        $webSite = WEB_SITE;
        $staticAdmin = STATIC_ADMIN;

        $this->assign([
            'webSite' => $webSite,
            'staticAdmin' => $staticAdmin,
            'attr' => $attr,
            'type' => $type,
            'brand' => $brand,
            'goods' => $goods,
            'goodsPage' => $goodsPage,

        ]);

        return $this->fetch();
    }

    //修改商品信息
    public function update()
    {
        $str = Request::instance()->param('str');
        $gid = Request::instance()->param('gid');

        //切割字符串
        $arr = explode('++_++',trim($str,'"'));
        //dump($str);
        //dump($arr);

        //当前时间datetime格式
        $currTime = date('Y-m-d H:i:s',time());
        $data['update_time'] = $currTime;

        //处理字段
        foreach ($arr as  $value) {
            $val = explode('===',$value);
            //dump($val);
            $data[$val[0]] = $val[1];

            //处理重量单位
            if ($val[0] == 'weight_unit') {

                $data['weight_unit'] = $val[1] == 1 ? 'g' : 'kg';
            }
        }

        //若修改了图片
        if (session('pic2')) {

            //处理图片
            $img = explode('+',session('pic2'));
            $data['big_logo'] = $img[0];
            $data['mid_logo'] = $img[1];
            $data['small_logo'] = $img[2];
        }
        //dump($data);

        //修改数据库
        $goods = GoodsModel::where(['goods_id'=>$gid])->update($data);
        //dump($goods);

        //是否修改成功
        if ($goods) {

            //清空上传session
            if (session('pic2')) {
                session('pic2', null);
            }

            echo json_encode(['state'=>3,'tip'=>'修改成功']);

        } else {

            echo json_encode(['state'=>4,'tip'=>'修改失败']);
        }
    }

    //回收商品 页面(伪删除)
    public function receive()
    {
        //常量
        $webSite = WEB_SITE;
        $staticAdmin = STATIC_ADMIN;

        //遍历商品表
        $goods = GoodsModel::where(['goods_del'=>1])->paginate(4);
        $goodsPage = $goods->render();

        $this->assign([
            'webSite' => $webSite,
            'staticAdmin' => $staticAdmin,
            'goods' => $goods,
            'goodsPage' => $goodsPage,

        ]);

        return $this->fetch();
    }




}